package com.jugheadzhou.auth.core.webapi.handler;

import com.jugheadzhou.auth.core.common.api.Result;
import com.jugheadzhou.auth.core.common.utils.JsonUtil;
import com.jugheadzhou.auth.core.webapi.anotation.ApiController;
import com.jugheadzhou.auth.core.webapi.anotation.ResponseNotIntercept;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.AnnotatedElement;

/**
 * @description: 返回数据拦截包装
 * @author: kwb
 * @create: 2020-04-19 22:57
 **/
@RestControllerAdvice(annotations = {ApiController.class})
public class ResponseHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> aClass) {
        AnnotatedElement annotatedElement = returnType.getAnnotatedElement();
        //有ResponseNotIntercept注解的不包装
        ResponseNotIntercept responseNotIntercept = AnnotationUtils.findAnnotation(annotatedElement, ResponseNotIntercept.class);
        return responseNotIntercept == null;
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {
        //本身不做包装
        if (data instanceof Result) {
            return data;
        }
        // String类型不能直接包装
        if (returnType.getGenericParameterType().equals(String.class)) {
            return JsonUtil.object2String(Result.success(data));
        }
        return Result.success(data);
    }


}
